<?php

/**
 * @author jigal
 *
 *
 */
class EventManager_UserController extends Zend_Controller_Action
{

    protected $_model = null;
    protected $_authService = null;
    protected $_logger = null;
    /**
     * (non-PHPdoc)
     * @see Controller/Zend_Controller_Action#init()
     */
    public function init()
    {
            /* Initialize action controller here */
            $this->_logger = Zend_Registry::get('log');
            $this->_logger->info('User Controller' . __METHOD__);
            $this->_model= new EventManager_Model_User();
            $this->_authService = new EventManager_Service_Authentication();
            $this->view->registerForm 	= $this->getRegistrationForm();
            $this->view->userForm 		= $this->getUserForm();
            //$this->view->editForm		= $this->getEditForm();
            $this->view->loginForm          = $this->getLoginForm();
    }
    /**
     *
     * @return unknown_type
     */
    public function indexAction()
    {
            $this->_logger->info('Usercontroller ' . __METHOD__);

            /*
            if (!$this->_model->checkAcl('updateUser')) {
                    return $this->_helper->redirectCommon('gotoLogin');
            }*/

            //$this->view->user = $this->_model->getUserById($this->_authService->getIdentity()->usr_id);
            /*
            if (null === $this->view->user) {
                    throw new SF_Exception('Onbekende gebruiker');
            }*/
            
            $this->view->userForm = $this->getUserForm()->populate($this->view->user->toArray());
    }
    /**
     *
     * @return unknown_type
     */
    public function saveAction()
    {

            $request = $this->getRequest();

            if(!$request->isPost()){
                    return $this->_helper->redirector('edit');
            }
            $form = $this->_forms['userEdit'];

            if(false === $this->_model->saveUser($request->getPost())){
                $form->setDescription('Het formulier kon niet worden verwerkt.
                Probeer het opnieuw');
                $this->view->form = $form;
                //return $this->render($form);
            }
    }
    /**
     *
     * @return unknown_type
     */
    public function registerAction()
    {
    }

    /**
     *
     * @return unknown_type
     */
    public function loginAction(){


    }
    /**
     *
     * @return unknown_type
     */
    public function logoutAction(){
            $this->_authService->clear();
            return $this->_helper->redirector->gotourl('/index/index');
    }
    /**
     *
     * @return unknown_type
     */
    public function authenticateAction(){
            $this->_logger->info('Usercontroller ' . __METHOD__);

            $request = $this->getRequest();

            if(!$request->isPost()){

                    return $this->_helper->redirector('login');
            }
            //validate the post data
            $form = $this->_forms['login'];



            if(!$form->isValid($request->getPost())){
                    return $this->render('login');
            }

            if(false === $this->_authService->authenticate($form->getValues())){

                    $this->_logger->Alert('Inlogen mislukt'.$form->getValues());
                    $form->setDescription('Het inloggen is mislukt. Probeer het opnieuw');
                    return $this->render('login');
            }

            return $this->_helper->redirector->gotoUrl('/event/index');
    }

    public function completeRegistrationAction(){
            $request = $this->getRequest();
            if(!$request->isPost()){
                    return $this->_helper->redirector('register');
            }
            if(false === ($id= $this->_model->registerUser($request->getPost()))){
                    return $this->render('register');
            }

            $this->sendConformationMail($request->getPost());

    }

    public function editAction(){

        $request = $this->getRequest();
        $form = $this->getEditForm();
        $this->view->form = $form;
        if($request->isPost()){
            if($form->isValid($request->getPost())){
                $this->_model->saveUser($this->getRequest()->getPost());
                $this->_redirect('index/index');
            }
        }

        /* Old

        $form = $this->getEditForm();
        if($this->getRequest()->isPost())
        {
            if($form->isValid($this->getRequest()->getPost()))
            {
                $result = $this->_model->saveUser($this->getRequest()->getPost());
                if($result == false){
                   $this->view->form = $form;
                }
            }

        }else{
            //puputlate forms with values from db
            echo('bye');
        }
        $this->view->form = $form;

         */
    }


    private function getRegistrationForm(){



            $urlHelper= $this->_helper->getHelper('url');
            $this->_forms['register'] = $this->_model->getForm('userRegister');
            $this->_forms['register']->setAction($urlHelper->url(array(
            'controller' => 'user',
            'action'	=>'complete-registration'
            ),
            'default'
            ));
            $this->_forms['register']->setMethod('post');
            $this->_forms['register'];


    return $this->_forms['register'];
    }

    private function getUserForm(){
            $urlHelper= $this->_helper->getHelper('url');
            $this->_forms['userEdit'] = $this->_model->getForm('userEdit');
            $this->_forms['userEdit']->setAction($urlHelper->url(array(
            'controller' => 'user',
            'action'	=>'save'
            ),
            'default'
            ));
            return $this->_forms['userEdit'];

    }

    private function getEditForm(){
            $user = new EventManager_Service_Authentication;
            $identity=$user->getIdentity();

            $urlHelper= $this->_helper->getHelper('url');
            $this->_forms['userUpdate'] = $this->_model->getForm('userUpdate');
            $this->_forms['userUpdate']->setAction($urlHelper->url(array(
            'controller' => 'user',
            'action'	=>'edit'
            ),
            'default'
            ));

            if(null != $identity)
            {
                    $this->_forms['userUpdate']->populate($identity->toArray());
            }else{
                    return $this->_helper->redirectCommon('gotoLogin');
            }

            return $this->_forms['userUpdate'];

    }

    private function getLoginForm()
    {
            $urlHelper = $this->_helper->getHelper('url');

            $this->_forms['login'] = $this->_model->getForm('userLogin');
            $this->_forms['login']->setAction($urlHelper->url(array(
        'controller' => 'user',
        'action'     => 'authenticate',
            ),
        'default'
        ));
        $this->_forms['login']->setMethod('post');

        return $this->_forms['login'];
    }

    /**
     *
     * @param unknown_type $postVariables
     */
    private function sendConformationMail($postVariables)
    {
            $mail = new SF_HtmlMailer();
            $mail->setSubject("Bedankt voor je registratie")
                     ->addTo('jigalroecha@gmail.com')
                     ->setViewParam('name',
                                                    ucfirst($postVariables['usr_firstname']).' ' .
                                                    ucfirst($postVariables['usr_surname']))
                     ->sendHtmlTemplate("registration.phtml");
    }

}